import 'dart:async';

import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:wallet_utils/base_router_config.dart';
import 'package:wallet_utils/log_util.dart';
import 'package:wallet_utils/report_widget/base/callback/base_callback.dart';
import 'package:wallet_utils/toast.dart';

import '../api/home_api.dart';
import '../bean/userAgreementBean.dart';
import 'state.dart';

class AuditProgressLogic extends GetxController with GetSingleTickerProviderStateMixin {
  final AuditProgressState state = AuditProgressState();
  late Animation<double> animation;
  late AnimationController controller;
  num? face;
  num? isShowIdCard;
  bool showContacts = false;
  num? channelAuthType;

  @override
  void onInit() {
    super.onInit();
    controller = AnimationController(duration: const Duration(seconds: 3), vsync: this);
    //进度条进度从0到1
    animation = Tween(begin: 0.0, end: 1.0).animate(controller)
      ..addListener(() {
        update();
      });
    controller.forward();

    animation.addListener(() {
      if (animation.value >= 0.3 && animation.value <= 0.4) {
        state.isAuditOne = true;
        update();
      } else if (animation.value >= 0.6 && animation.value <= 0.7) {
        state.isAuditTwo = true;
        update();
      } else if (animation.value >= 1.0) {
        state.isAuditThree = true;
        update();
      }
      if (animation.value >= 1.0) {
        getUser2WhereApi();
      }
    });
    if (Get.arguments != null) {
      face = Get.arguments['face'];
      showContacts = Get.arguments['showContacts'];
      isShowIdCard = Get.arguments['isShowIdCard'];
      channelAuthType = Get.arguments['channelAuthType'];
    }
    // if (state.countdownTime == 0) {
    //   state.countdownTime = 3;
    //   //开始倒计时
    //   startCountdownTimer();
    // }
  }

  void startCountdownTimer() {
    const oneSec = Duration(seconds: 1);
    // ignore: prefer_function_declarations_over_variables
    var callback = (timer) {
      if (state.countdownTime < 1) {
        state.timer.cancel();
      } else {
        state.countdownTime = state.countdownTime - 1;
        state.progress = (state.progress)! + 0.1;
      }
      update();
    };

    state.timer = Timer.periodic(oneSec, callback);
  }

  void getUser2WhereApi() async {
    HomeApi.getUser2WhereApi(BaseCallback(onSuccess: (map) {
      UserAgreementBean userAgreementBean = UserAgreementBean.fromJson(map);
      if (userAgreementBean.data != null) {
        state.content = userAgreementBean.data!.content!;
        if (userAgreementBean.data!.companyName!.isNotEmpty) {
          Get.toNamed(BaseRouterConfig.offlineProduct, arguments: {
            'productInfo': userAgreementBean.data,
            'face': face,
            'showContacts': showContacts,
            'isShowIdCard': isShowIdCard,
            'channelAuthType': channelAuthType
          });
        } else {
          jumpPage();
        }
      }
    }, onError: (msg) {
      Future.delayed(const Duration(milliseconds: 500), () {
        ToastUtils.showToast(msg ?? "");
      });
    }));
  }

  jumpPage() async {
    if (isShowIdCard == 0) {
      await preposition();
    } else {
      if (channelAuthType == 2) {
        Get.toNamed(BaseRouterConfig.identityCertification, arguments: {
          'isShowIncoming': false,
          'face': face,
          'showContacts': showContacts,
          'channelAuthType': channelAuthType,
        });
      } else {
        await preposition();
      }
    }
  }

  Future<void> preposition() async {
    if (showContacts) {
      Get.toNamed(BaseRouterConfig.contactPerson, arguments: {
        'isShowIncoming': false,
        'face': face,
        'isShowIdCard': isShowIdCard,
        'channelAuthType': channelAuthType,
      });
    } else if (face == 1 && !showContacts) {
      await jumpFace();
    } else if (face == 0 && !showContacts) {
      Get.toNamed(BaseRouterConfig.auditRejection);
    }
  }

  Future<void> jumpFace() async {
    WidgetsFlutterBinding.ensureInitialized();
    state.cameras = await availableCameras();

    /// 获取设备摄像头，默认0:后置 1:前置
    state.firstCamera = state.cameras!.first;
    Get.toNamed(BaseRouterConfig.faceRecognition, arguments: {
      'isShowIncoming':false,
      'camera': state.cameras,
    });
  }
}
